package com.s63.modules.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.s63.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户登录成功后，保存到redis的对象
 */
@Data
public class LoginUser implements UserDetails {
    private User user;
    // 保存用户对应的角色key
    private List<String> roleKeyList;
    // 保存用户对应的权限字符串
    private List<String> permsList;

    //使用@PreAuthorize时，会自动调用该方法获取用户的权限或角色
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        list.addAll(permsList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        list.addAll(roleKeyList.stream().map(roleKey -> new SimpleGrantedAuthority("ROLE_" + roleKey)).collect(Collectors.toList()));
        return list;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
